import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:get/get.dart';
import 'package:roswell_rgbw/commont/bg_page.dart';
import 'package:roswell_rgbw/modules/settings/setting_controller.dart';

import '../../const/const.dart';
import 'search_row.dart';

class Setting extends StatefulWidget {
  const Setting({super.key});
  @override
  State<Setting> createState() => _SettingState();
}

const String filterName = 'QHM';

class _SettingState extends State<Setting> implements BLESearchTableViewDelegate {
  BLESearchTableView? _tableView;
  BLESearchTableViewDelegate? delegate;
  final controller = Get.find<SettingController>();
  @override
  void initState() {
    super.initState();
    delegate = this;
    _tableView = BLESearchTableView(
      filterName: [filterName],
      agreement: delegate,
      contentColor: Color(0xFF252934),
      // dragDecoration: BoxDecoration(
      //   color: themeColor,
      //   borderRadius: BorderRadius.circular(10),
      //   boxShadow: [BoxShadow(color: Colors.white.withOpacity(0.5), blurRadius: 2)],
      // ),
      // dragTransformXY: Offset(1.0, 1.2),
      bgViewForHeader: (child) => Container(color: Colors.transparent, child: child),
      bgViewForFooter: (child) => Container(color: Colors.transparent, child: child),
    );
  }

  @override
  Widget build(BuildContext context) {
    controller.refreshTable = (() {
      _tableView?.refreshKey?.currentState?.show();
    });
    controller.addGroup = ((name) {
      _tableView?.addGroup(name);
    });
    controller.updateManagerState = (() {
      _tableView?.isGroupManager = controller.isGroupManager.value;
    });
    double statusBarHeight = MediaQuery.of(context).padding.top;
    double appBarHeight = AppBar().preferredSize.height;
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        title: Obx(() {
          return controller.isGroupManager.value ? Text('GROUP MANAGEMENT') : Image.asset(assets.LOGO, height: 30);
        }),
        leading: IconButton(onPressed: () => Get.back(), icon: Image.asset(assets.back, width: 25, height: 25)),
      ),
      extendBody: true,
      backgroundColor: Colors.transparent,
      body: BgPage(
        child: Obx(() {
          return Stack(
            children: [
              Positioned(
                left: 10,
                right: 10,
                top: statusBarHeight + appBarHeight,
                height: 40,
                child: const Align(
                  alignment: Alignment.centerLeft,
                  child: Text('Ungrouped Devices', style: TextStyle(color: Colors.white, fontSize: 18)),
                ),
              ),

              ///tableview
              Positioned(
                bottom: 80,
                left: 10,
                right: 10,
                top: statusBarHeight + appBarHeight + 40,
                child: Container(
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(10), color: Colors.transparent),
                  clipBehavior: Clip.hardEdge, // 通过clipBehavior来切割子组件
                  child: _tableView ?? Container(),
                ),
              ),

              ///底部按钮
              Positioned(
                bottom: 20,
                right: 0,
                left: 0,
                height: 40,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: (controller.isGroupManager.value ? controller.footerIcons : controller.footerList).map((
                    $0,
                  ) {
                    if (controller.isGroupManager.value) {
                      return SizedBox(
                        width: 40,
                        height: 40,
                        child: InkWell(
                          borderRadius: BorderRadius.circular(25),
                          onTapUp: (_) => controller.clickFooter(context, $0),
                          child: Image.asset($0, width: 20, height: 40),
                        ),
                      );
                    }
                    return Material(
                      color: Colors.transparent, // 保证 Material 背景透明
                      child: Ink(
                        decoration: BoxDecoration(
                          color: Colors.black, // 设置背景颜色
                          borderRadius: BorderRadius.circular(4), // 圆角
                          border: BoxBorder.all(color: themeColor, width: 1),
                        ),
                        child: InkWell(
                          borderRadius: BorderRadius.circular(4),
                          onTapUp: (_) => controller.clickFooter(context, $0),
                          child: Padding(
                            padding: const EdgeInsets.only(left: 10, right: 10),
                            child: Center(
                              child: Text($0, style: const TextStyle(fontSize: 16, color: Colors.white)),
                            ),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  @override
  List<RowModel> listModelForFooter(String appVersion) => [];

  @override
  List<RowModel> listModelForHeader(String appVersion) => [];

  @override
  List<RowModel> listModelForSection(List<String> list) {
    return list
        .map(
          ($0) => RowModel(
            text: $0,
            height: 40,
            textStyle: const TextStyle(fontSize: 18, color: Colors.white),
            lineColor: Colors.grey,
            lineHeight: 1,
            bgColor: Colors.transparent,
            iconName: assets.delete,
            leftOffset: 0,
            showLine: false,
            iconSize: 20,
          ),
        )
        .toList();
  }

  @override
  void methodForClickBLESearchTableView(BLESearchTableViewClickType type, String tag) {}

  @override
  Widget viewForRowInSection(DSPeripheral peripheral, int section, int row, bool isOn) {
    var type = SearchItemType.middlle;
    if (row == 0 && _tableView!.deviceList[section].values.first.length - 1 == row) {
      type = SearchItemType.topBottom;
    } else if (row == 0) {
      type = SearchItemType.top;
    } else if (row == _tableView!.deviceList[section].values.first.length - 1) {
      type = SearchItemType.bottom;
    }
    return SearchItem(
      device: peripheral,
      isManager: controller.isGroupManager.value,
      type: type,
      onSelect: () => _tableView?.clickDevice(section, row),
      onPressLongToChangeName: () => _tableView?.changeDeviceName(section, row, peripheral.peripheral),
    );
  }
}
